/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gravitee.policy.wjy;

import io.gravitee.gateway.api.ExecutionContext;
import io.gravitee.gateway.api.Request;
import io.gravitee.gateway.api.Response;
import io.gravitee.policy.api.PolicyChain;
import io.gravitee.policy.api.annotations.OnRequest;
import io.gravitee.policy.wjy.configuration.WjyPolicyConfiguration;
import net.minidev.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
@SuppressWarnings("unused")
public class WjyPolicy {
    private final WjyPolicyConfiguration wjyPolicyConfiguration;
    private static final Logger LOGGER = LoggerFactory.getLogger(WjyPolicy.class);

    public WjyPolicy(WjyPolicyConfiguration wjyPolicyConfiguration) {
        this.wjyPolicyConfiguration = wjyPolicyConfiguration;
    }

    @OnRequest
    public void onRequest(Request request, Response response, ExecutionContext executionContext, PolicyChain policyChain) {
        Map<String, String> paramMap = request.parameters().toSingleValueMap();
        String oldName = null;
        if(wjyPolicyConfiguration == null) {
            LOGGER.info("wjyPolicyConfiguration为空");
        } else {
            LOGGER.info("wjyPolicyConfiguration的name：{}", wjyPolicyConfiguration.getName());
            oldName = wjyPolicyConfiguration.getName();
        }
        LOGGER.info("paramMap的值为:{}", JSONObject.toJSONString(paramMap));

        response.headers().add("oldName", oldName);
        response.headers().add("newName", "new-wangjianyu");

        Object nameValue = executionContext.getAttribute(wjyPolicyConfiguration.getName());
        if(nameValue == null) {
            nameValue = "null";
        }
        LOGGER.info("nameValue:{}", nameValue.toString());
        response.headers().add("nameValue", nameValue.toString());
        policyChain.doNext(request, response);
    }
}
